package utils

import (
	"fmt"
	"time"
	"strings"
	"strconv"
	"errors"
)

//创建Token
func CreateToken(uid string) (token string, err error) {
	t := fmt.Sprintf("%d", time.Now().Unix())
	token = fmt.Sprintf("%s@%s", uid, MD5ToString(uid+"@"+t))
	if err = Set(uid, token, time.Hour*24); err != nil {
		return
	}
	return
}

//获取uid
func GetUidByToken(token string) (uid int, err error) {
	if len(token) == 0 {
		err = errors.New("未获取到用户信息")
		return
	}
	info := strings.Split(token, "@")
	var cache string
	cache, err = Get(info[0])
	if err != nil {
		err = errors.New("用户会话过期")
		return
	}
	if cache != token {
		err = errors.New("用户已在其他地方登录")
		return
	}
	uid, err = strconv.Atoi(info[0])
	if err != nil {
		err = errors.New("获取用户信息失败")
		return
	}
	return
}
